<template>
  <view class="homePage">
    <view class="toolBar">
      <uni-title class="title" type="h1" title="任务列表" align="left"/>
      <button class="btnCls" @click="handleAdd">添加</button>
    </view>
    <view class="content">
      <uni-card :title="'今日待办 ' + todoTaskList.length " class="cardClass">
        <view v-if="todoTaskList.length == 0">
          <uni-title class="title" type="h1" title="今日任务全部完成" align="center"/>
        </view>
        <view v-else class="container" v-for="taskList in todoTaskList">
          <view class="left">
            <radio class="taskStatus" @click="handleChecked(taskList)"/>
          </view>
          <view class="right" @click="handleClickTaskList(taskList)">
            <view class="top">
              <text class="taskName">{{ taskList.title }}</text>
            </view>
            <view class="bottom">
              <uni-tag class="taskFrequency" :inverted="true" :text="getFrequency(taskList.frequency)" type="primary"/>
              <text class="taskNeedTime">{{ taskList.needTime }}分钟</text>
              <text class="taskNeedTime">{{ taskList.startDate && taskList.endDate.split('T')[0] }}</text>
              <text class="taskLeftTime">{{ getLeftTime(taskList.endDate) }}</text>
            </view>
          </view>
        </view>
      </uni-card>
      <uni-card :title="'今日已完成 '+ finishedTaskList.length" class="cardClass">
        <view v-if="finishedTaskList.length == 0">
          <uni-title class="title" type="h1" title="今日还需努力 ヾ(◍°∇°◍)ﾉﾞ" align="center"/>
        </view>
        <view v-else class="container" v-for="taskList in finishedTaskList">
          <view class="left">
            <radio class="taskStatus" checked="true" @click="handleChecked(taskList)"/>
          </view>
          <view class="right" @click="handleClickTaskList(taskList)">
            <view class="top">
              <text class="taskName">{{ taskList.title }}</text>
            </view>
            <view class="bottom">
              <uni-tag class="taskFrequency" :inverted="true" :text="getFrequency(taskList.frequency)" type="primary"/>
              <text class="taskNeedTime">{{ taskList.needTime }}分钟</text>
              <text class="taskNeedTime">{{ taskList.startDate && taskList.startDate.split('T')[0] }}</text>
            </view>
          </view>
        </view>
      </uni-card>
      <uni-card title="历史任务" class="cardClass">
        <template v-slot:title>
          <view class="toolBar history-tool-bar">
            <uni-title class="title" type="h1" title="历史任务" align="left"/>
            <button class="btnCls" @click="()=>  loadHistoryTaskListData()">查询</button>
          </view>
        </template>
        <view v-if="historyTaskList.length == 0">
          <uni-title class="title" type="h1" title="荒芜 ~ 空空如也" align="center"/>
        </view>
        <view v-else class="container" v-for="taskList in historyTaskList" disabled>
          <view class="left">
            <uni-tag v-if="taskList.status === 2" text="已完成" type="primary"/>
            <uni-tag v-else text="过期" type="error"/>
          </view>
          <view class="right" @click="handleClickTaskList(taskList)">
            <view class="top">
              <text class="taskName">{{ taskList.title }}</text>
            </view>
            <view class="bottom">
              <uni-tag class="taskFrequency" :inverted="true" :text="getFrequency(taskList.frequency)" type="primary"/>
              <text class="taskNeedTime">{{ taskList.needTime }}分钟</text>
              <text class="taskNeedTime">{{ taskList.startDate && taskList.startDate.split('T')[0] }}</text>
            </view>
          </view>
        </view>
        <uni-load-more :status="loading"/>
      </uni-card>
    </view>
  </view>
</template>

<script setup lang="ts">
import {effect, ref} from 'vue'
import {
  listMyHistoryTaskListByPageUsingPost,
  listMyTaskListByPageUsingPost,
  updateTaskListStatusUsingPost
} from "@/services/api/taskListController";
import {onPullDownRefresh} from "@dcloudio/uni-app";

const getDate = (type: string) => {
  const date = new Date();
  date.setDate(date.getDate() - 1);

  if (type === 'startDate') {
    date.setMonth(date.getMonth() - 1);
    // 2024-10-26T16:00:00.000Z
    return date.toISOString().split("T")[0] + 'T00:00:00.000Z';
  } else {
    return date.toISOString().split("T")[0] + 'T23:59:59.000Z';
  }
}

const loading = ref<string>('more')
const isFirstLoad = ref<boolean>(true)
const total = ref<number>(0)
const current = ref<number>(1)
const todoTaskList = ref<API.TaskList[]>([])
const finishedTaskList = ref<API.TaskList[]>([])
const historyTaskList = ref<API.TaskList[]>([])
const defaultHistoryTaskListParams = ref<API.TaskListQueryRequest>({
  sortField: 'startDate',
  sortOrder: 'descend',
  pageSize: 20,
  current: 1,
  startDate: getDate('startDate'),
  endDate: getDate('endDate'),
})

const frequencyMap = {
  DAILY: '日',
  WEEKLY: '周',
  MONTHLY: '月'
}
const getFrequency = (val: any) => {
  // @ts-ignore
  return frequencyMap[val] || '无';
}

const getLeftTime = (endDate: string) => {
  const end = new Date(endDate);
  const current = new Date();
  // @ts-ignore
  let difference = end - current;
  let hours = Math.floor(difference / (1000 * 60 * 60));
  let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));

  return hours + 'h' + minutes + 'm';
}

/**
 * 查询任务列表数据
 */
const loadTaskListData = async () => {
  const res = await listMyTaskListByPageUsingPost({}) as any;

  const data = res.records as API.TaskList[];

  todoTaskList.value = [];
  finishedTaskList.value = [];

  if (data) {
    data.map(taskList => {
      if (taskList.status == 1) {
        todoTaskList.value.push(taskList);
      }
      if (taskList.status == 2) {
        finishedTaskList.value.push(taskList);
      }
    })
  }
}

/**
 * 加载历史数据
 */
const loadHistoryTaskListData = async () => {
  if (total.value !== 0 && historyTaskList.value.length === total.value) {
    loading.value = 'noMore';
    return;
  }

  if (isFirstLoad.value) {
    isFirstLoad.value = false
  } else {
    defaultHistoryTaskListParams.value.current = current.value + 1;
  }
  loading.value = 'loading';
  const res = await listMyHistoryTaskListByPageUsingPost({...defaultHistoryTaskListParams.value}) as any;
  if (res) {
    total.value = res.total;
    const data = res.records as API.TaskList[];
    if (data.length === 0) {
      loading.value = 'noMore';
      return;
    }
    historyTaskList.value.push(...data);
  }

  if (historyTaskList.value.length === total.value) {
    loading.value = 'noMore';
  } else {
    loading.value = 'more';
  }
}


/**
 * 完成或取消完成
 * @param taskList
 */
const handleChecked = async (taskList: API.TaskList) => {
  uni.showLoading({
    title: '加载中'
  });
  const status = (taskList.status == 1 ? 2 : 1);
  const data = await updateTaskListStatusUsingPost({id: taskList.id, status});
  if (data) {
    await loadTaskListData();
  }
  uni.hideLoading();
}

const handleClickTaskList = (taskList: API.TaskList) => {
  if (taskList.id) {
    uni.navigateTo({
      url: `/pages/home/taskList/TaskListDetail?id=${taskList.id}`
    });
  }
}


/**
 * 添加事件
 */
const handleAdd = () => {
  uni.redirectTo({
    url: '/pages/home/taskList/TaskListAdd'
  });
}

/**
 * 下拉刷新
 */
onPullDownRefresh(async () => {
  await loadTaskListData();
  uni.stopPullDownRefresh();
  uni.showToast({
    icon: "success",
    title: "刷新成功",
    duration: 2000
  });
})

effect(() => {
  loadTaskListData();
  loadHistoryTaskListData();
})

</script>

<style scoped>
html, body, .app {
  height: 100%;
  margin: 0;
}

.homePage {
  //height: 100%;
  min-height: 100vh;
  background: linear-gradient(to right, #ebf1fd, #ffffff);

  .toolBar {
    margin: 2px 0 0 0;
    display: flex;
    justify-content: space-between; /* 按钮之间的间距 */
    align-items: center; /* 垂直居中 */
    border: 1px solid #bbc7e0;
    border-radius: 2px;

    .btnCls {
      width: 30vw;
      background: linear-gradient(to bottom, #ebf1fd, #ffffff); /* 渐变背景 */
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影 */
      transition: all 0.2s ease; /* 悬浮过渡效果 */
    }

    .btnCls:hover {
      transform: translateY(-2px); /* 悬浮时上移 */
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 悬浮时阴影加深 */
    }
  }

  .history-tool-bar {
    border: 0;

    .btnCls {
      margin-top: 2px;
    }
  }


  .content {
    padding-bottom: 5vh;
  }

  .title {
    font-size: 36rpx;
    color: #8f8f94;
    margin-left: 5px;
  }

  .cardClass {
    background-color: transparent;
  }

  .container {
    margin-bottom: 5px;
    background-color: white;
    padding: 5px;
    display: flex;
    align-items: center;
    border: 1px solid #ccc; /* 添加边框 */
    border-radius: 8px; /* 添加圆角 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  }

  .left {
    margin-right: 16px;
  }

  .right {
    display: flex;
    flex-direction: column;
  }

  .top {
    margin-bottom: 8px;
  }

  .bottom {
    display: flex;
    align-items: center;
  }

  .taskStatus {
    /* 根据需要调整样式 */
  }

  .taskName {
    font-size: 14px;
    font-weight: bold; /* 加粗 */
    color: #000; /* 黑色 */
  }

  .taskFrequency {
    /* 根据需要调整样式 */
  }

  .taskNeedTime {
    margin-left: 15px;
  }

  .taskLeftTime {
    margin-left: 15px;
    color: #ff0000;
  }


}


</style>
